<template>
  <div class="stock_info" v-if="stockInfo.detail">
    <!-- 股票头部标题 -->
    <div class="stock_info_top">
      <img
        class="show_icon"
        :src="showis ? imgHover : img"
        alt=""
        @click="quotationBtn"
      />
      {{ stockInfo.detail.name }} {{ stockInfo.detail.symbol }}
      <span
        :class="
          Number(qutationData.latestPrice) > Number(stockInfo.detail.close)
            ? 'red'
            : Number(qutationData.latestPrice) == Number(stockInfo.detail.close)
            ? ''
            : 'green'
        "
        class="latestPrice"
        >{{
          Number(qutationData.latestPrice) | toFixed(stockInfo.detail.precision)
        }}</span
      >

      <!-- 涨跌额 -->
      <span
        :class="
          Number(qutationData.gain) > 0
            ? 'red'
            : Number(qutationData.gain) == 0
            ? ''
            : 'green'
        "
        >{{ qutationData.gain > 0 ? "+" : ""
        }}{{
          ((qutationData.chg * 100) / 100).toFixed(stockInfo.detail.precision)
        }}</span
      >
      <span
        :class="
          Number(qutationData.gain) > 0
            ? 'red'
            : Number(qutationData.gain) == 0
            ? ''
            : 'green'
        "
        >{{ qutationData.gain > 0 ? "+" : ""
        }}{{ Number(qutationData.gain * 100) | toFixed(2) }}%</span
      >
      <div class="rightIcon">
        <img @click="flasher" :src="flasherIcon" alt="" />
        <img
          @click="editWarn"
          :src="stockInfo.detail.warnId == 0 ? warnIcon[0] : warnIcon[1]"
          alt=""
        />
        <img
          @click="editCheck"
          :src="stockInfo.detail.optionId == 0 ? ckeckIcon[0] : ckeckIcon[1]"
          alt=""
        />
      </div>
    </div>
    <!-- 仅美股有,盘前时间显示盘前交易；
      {{$t('info.info_stock.56hzcquanng0')}}
      {{$t('info.info_stock.56hzcquaoq40')}}
      {{$t('info.info_stock.56hzcquaoyw0')}} -->
    <!-- 1：盘前交易 2：交易中 3：盘后交易 4：已收盘 -->
    <div
      class="panQH"
      v-if="
        stockInfo.detail.market == 'US' &&
        stockInfo.detail.securityType != 2 &&
        stockInfo.market.status !== 2
      "
    >
      <div class="pan_left">
        <div class="pan_title">
          <span
            v-if="stockInfo.market.status == 1 || stockInfo.market.status == 3"
            >{{ stockInfo.market.status | PanStatus(te) }}</span
          >
          <span v-if="stockInfo.market.status == 4">{{
            3 | PanStatus(te)
          }}</span>
          <img
            @click="tipVisible = true"
            class="label_icon"
            src="@/assets/img/icon_bbxxh.png"
            alt=""
          />
        </div>
        <div v-if="stockInfo.detail.biddingVolume == 0">
          {{ $t("info.info_stock.56hzcquap5k0") }}
        </div>
        <div class="pan_data" v-else>
          <!-- 盘前盘后价格 -->
          <span
            :class="
              Number(stockInfo.detail.biddingPrice) >
              Number(stockInfo.detail.latestPrice)
                ? 'red'
                : Number(stockInfo.detail.biddingPrice) ==
                  Number(stockInfo.detail.latestPrice)
                ? ''
                : 'green'
            "
            >{{
              Number(stockInfo.detail.biddingPrice).toFixed(
                stockInfo.detail.precision
              )
            }}</span
          >
          <!-- 盘前涨跌额 -->
          <span
            :class="
              Number(stockInfo.detail.biddingPrice) >
              Number(stockInfo.detail.latestPrice)
                ? 'red'
                : Number(stockInfo.detail.biddingPrice) ==
                  Number(stockInfo.detail.latestPrice)
                ? ''
                : 'green'
            "
            >{{ stockInfo.detail.biddingChg > 0 ? "+" : ""
            }}{{ Number(stockInfo.detail.biddingChg).toFixed(2) }}</span
          >
          <span
            :class="
              Number(stockInfo.detail.biddingGain) > 0
                ? 'red'
                : Number(stockInfo.detail.biddingGain) == 0
                ? ''
                : 'green'
            "
            >{{ stockInfo.detail.biddingGain > 0 ? "+" : ""
            }}{{ Number(stockInfo.detail.biddingGain * 100).toFixed(2) }}%</span
          >
        </div>
      </div>
      <div class="pan_center">
        <div class="pan_item">
          <span>{{ $t("info.info_stock.56hzcquapc00") }}</span>
          <span v-if="stockInfo.detail.biddingVolume == 0">--</span>
          <span
            v-else
            :class="
              Number(stockInfo.detail.biddingHigh) >
              Number(stockInfo.detail.latestPrice)
                ? 'red'
                : Number(stockInfo.detail.biddingHigh) ==
                  Number(stockInfo.detail.latestPrice)
                ? ''
                : 'green'
            "
            >{{
              stockInfo.detail.biddingHigh != 0
                ? Number(stockInfo.detail.biddingHigh).toFixed(
                    stockInfo.detail.precision
                  )
                : "--"
            }}</span
          >
        </div>
        <div class="pan_item">
          <span>{{ $t("info.info_stock.56hzcquapio0") }}</span>
          <span v-if="stockInfo.detail.biddingVolume == 0">--</span>
          <span
            v-else
            :class="
              Number(stockInfo.detail.biddingLow) >
              Number(stockInfo.detail.latestPrice)
                ? 'red'
                : Number(stockInfo.detail.biddingLow) ==
                  Number(stockInfo.detail.latestPrice)
                ? ''
                : 'green'
            "
            >{{
              stockInfo.detail.biddingLow != 0
                ? Number(stockInfo.detail.biddingLow).toFixed(
                    stockInfo.detail.precision
                  )
                : "--"
            }}</span
          >
        </div>
        <div class="pan_item">
          <span>{{ $t("info.info_stock.56hzcquapqw0") }}</span>
          <span v-if="stockInfo.detail.biddingVolume != 0">
            {{ stockInfo.detail.biddingVolume | changeNum(te)
            }}{{ $t("account_dialog.charging_dialog.56htmhsg8eo0") }}
          </span>
          <span v-else>--</span>
        </div>
        <div class="pan_item">
          <span>{{ $t("info.info_stock.56hzcquapx40") }}</span>
          <span v-if="stockInfo.detail.biddingAmount != 0">{{
            stockInfo.detail.biddingAmount | changeNum(te)
          }}</span>
          <span v-else>--</span>
        </div>
      </div>
      <div class="pan_right">
        <span v-if="stockInfo.detail.biddingAmount != 0" class="time">{{
          stockInfo.detail.biddingTime | toNewYork
        }}</span>
        <span>{{ $t("info.info_stock.56hzcquaq3s0") }}</span>
      </div>
    </div>
    <el-tabs
      v-model="activeName"
      @tab-click="handleClick"
      class="stock_info_type"
      v-if="isRefresh"
    >
      <el-tab-pane :label="$t('info.info_stock.56hzcquaqa80')" name="first">
        <info-line
          :infoCode="Details_data"
          :height="childHeight"
          :showis="showis"
          :RefreshIndex="RefreshIndex"
          ref="kLine"
          v-if="isRefresh"
        ></info-line>
      </el-tab-pane>
      <el-tab-pane :label="$t('info.info_stock.56hzcquaqg40')" name="second">
        <InfoNews
          ref="getNews"
          :infoCode="Details_data"
          :height="childHeight"
          :RefreshIndex="RefreshIndex"
          v-if="isRefresh && activeName == 'second'"
        ></InfoNews>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('info.info_stock.56hzcquaqmg0')"
        name="third"
        v-if="stockInfo.detail.securityType == 1"
      >
        <info-post
          :infoCode="Details_data"
          :height="childHeight"
          :RefreshIndex="RefreshIndex"
          v-if="isRefresh && activeName == 'third'"
          ref="infoPosts"
        ></info-post>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('info.info_stock.56hzcquaqs80')"
        name="fourth"
        v-if="stockInfo.detail.securityType == 1"
      >
        <InfoFinance
          :infoCode="Details_data"
          :height="childHeight"
          :RefreshIndex="RefreshIndex"
          ref="infoFourth"
          v-if="isRefresh && activeName == 'fourth'"
        ></InfoFinance>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('info.info_stock.56hzcquaqyk0')"
        name="fifth"
        v-if="stockInfo.detail.securityType == 1"
      >
        <InfoProfile
          :infoCode="Details_data"
          :stockType="stockInfo.detail.securityType"
          :height="childHeight"
          :RefreshIndex="RefreshIndex"
          ref="infoFifths"
          v-if="isRefresh"
        ></InfoProfile>
      </el-tab-pane>
    </el-tabs>
    <WarnDialog
      ref="warnDia"
      :show="IsWarn"
      :warnNavKey="navKey"
      @hides="hiddenWarn"
    >
    </WarnDialog>
    <!-- 2：盘前盘后说明 -->
    <el-dialog
      width="700px"
      :visible="tipVisible"
      :append-to-body="true"
      :show-close="false"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="5%"
      class="tip_dialog"
    >
      <Explain @hidePan="hidePan" :type="2"></Explain>
    </el-dialog>
  </div>
</template>
<script>
import { get_details } from "@/assets/js/API/market.js";
import {post_optional_delete, post_insert} from '@/assets/js/API/user.js';
import InfoNews from "@/components/info/InfoNews.vue";
import infoPost from "@/components/info/info_post.vue";
import InfoProfile from "@/components/info/InfoProfile.vue";
import InfoFinance from "@/components/info/InfoFinance.vue";
import WarnDialog from "@/components/header/warn/WarnDialog";
import infoLine from "@/components/info/info_line";
import Explain from "@/components/tip/explain";
import dayjs from "dayjs";
import * as timezone from "dayjs/plugin/timezone"; // import plugin
import * as utc from "dayjs/plugin/utc"; // import plugin
// 配置使用处理相对时间的插件
dayjs.extend(utc);
dayjs.extend(timezone);
export default {
  components: {
    InfoNews,
    infoPost,
    InfoProfile,
    InfoFinance,
    WarnDialog,
    infoLine,
    Explain,
  },
  props: ["stockCode", "showis"],
  inject: ["reload"],
  data() {
    return {
      activeName: "first",
      display: "none",
      list: {},
      childHeight: null,
      timeClick: null,
      Details_data: null,
      url: "",
      showHide: true,
      img: require("@/assets/img/icon_sq.png"),
      imgHover: require("@/assets/img/icon_sql.png"),
      flasherIcon: require("@/assets/img/icon_sx.png"),
      warnIcon: [
        require("@/assets/img/icon_xxtxh.png"),
        require("@/assets/img/icon_yjls.png"),
      ],
      ckeckIcon: [
        require("@/assets/img/icon_sch.png"),
        require("@/assets/img/icon_sc.png"),
      ],
      IsWarn: 99, // 预警列表显示
      navKey: 0,
      nowTime: new Date(),
      RefreshIndex: 1,
      tipVisible: false, // 盘前详情对话框
      qutationData: {
        latestPrice: "",
        gain: "",
        chg: "",
      }, // 股票行情数据
      isRefresh: true, // 刷新重置组件
      setSymbolTime: null, // 股票涨跌定时器
    };
  },
  mounted() {
    var _this = this;
    this.childHeight = $(".homeCenter").height() - 80;
    _this.getDetail();
  },
  beforeDestroy() {
    if (this.setSymbolTime) {
      window.clearInterval(this.setSymbolTime); //关闭股票详情5秒定时器
      this.setSymbolTime = null;
    }
  },
  filters: {
    // 纽约时间为GMT-5
    toNewYork(val) {
      return dayjs(val * 1000)
        .tz("America/Toronto")
        .format("HH:mm");
    },
    date(val) {
      return dayjs(val * 1000).format("HH:mm");
    },
  },
  methods: {
    //点击显示隐藏自选
    quotationBtn() {
      this.$emit("optionClick");
      // 重新获取K线图宽高
    },
    // setVal() {
    //   var _this = this;
    //   _this.timeClick = setInterval(() => {
    //     // _this.getDetail();
    //   }, 5000);
    // },
    hidePan() {
      this.tipVisible = false;
    },
    stockClick(index, item) {
      this.key_stock = index;
      this.itemStock = item;
    },
    handleClick(tab, event) {
      if (tab.index == 1) this.$refs.getNews.getdata();
      else if (tab.index == 2) this.$refs.infoPosts.getdata();
      else if (tab.index == 3) this.$refs.infoFourth.postClick();
      else if (tab.index == 4) this.$refs.infoFifths.getdata();
    },
    // 获取股票信息
    async getDetail() {
      if (!this.Details_data) return;
      const res = await get_details(this.Details_data);
      if (res.code != 1) return this.$message.error(res.msg);
      if (this.setSymbolTime) {
        this.$nextTick(() => {
          this.$set(
            this.qutationData,
            "latestPrice",
            res.data.detail.latestPrice
          );
          this.$set(this.qutationData, "gain", res.data.detail.gain);
          this.$set(this.qutationData, "chg", res.data.detail.chg);
        });
      } else {
        this.list = res.data.detail;
        this.list.id = res.data.detail.warnId;
        this.$store.dispatch("SetStock", res.data);
        this.Details_data.currency = res.data.detail.currency;
      }
      //console.log(res.data.detail,'submit1')
    },
    // 刷新股票信息
    flasher() {
      // this.RefreshIndex++;
      this.isRefresh = false;
      switch (this.activeName) {
        case "first":
          this.$nextTick(() => {
            this.isRefresh = true;
          });
          this.getDetail();
          break;
        case "second":
          this.isRefresh = true;
          this.$refs.getNews.list = [];
          this.$refs.getNews.submit.page = 1;
          this.$refs.getNews.loading = true;
          this.$refs.getNews.noMore = false;
          this.$refs.getNews.getdata();
          break;
        case "third":
          this.isRefresh = true;
          this.$refs.infoPosts.list = [];
          this.$refs.infoPosts.loading = true;
          this.$refs.infoPosts.noMore = false;
          this.$refs.infoPosts.submit.page = 1;
          this.$refs.infoPosts.getdata();
          break;
        case "fourth":
          this.$nextTick(() => {
            this.isRefresh = true;
          });
          this.$refs.infoFourth.threeOption = null;
          this.$refs.infoFourth.threeOption = null;
          this.$refs.infoFourth.twoOption = null;
          this.$refs.infoFourth.twoChart = null;
          this.$refs.infoFourth.postClick();
          break;
        case "fifth":
          this.isRefresh = true;
          this.$refs.infoFifths.info = {};
          this.$refs.infoFifths.list = [];
          this.$refs.infoFifths.company = [];
          this.$refs.infoFifths.UlListSize = [];
          this.$refs.infoFifths.UlCompanySize = null;
          this.$refs.infoFifths.tableList = [];
          this.$refs.infoFifths.getdata();
          break;
        default:
          this.$nextTick(() => {
            this.isRefresh = true;
          });
          this.getDetail();
      }
    },
    hiddenWarn() {
      this.IsWarn = 99;
    },
    // 添加预警或取消预警
    async editWarn() {
      // warnID: 0，不存在预警,新建预警信息，否则存在,则修改预警
      if (this.stockInfo.detail.warnId == 0) {
        this.IsWarn = 0;
        this.navKey = 1;
        setTimeout(() => {
          this.$refs.warnDia.checkNav(1);
        }, 100);
      } else {
        this.IsWarn = 0;
        setTimeout(() => {
          this.$refs.warnDia.getWarnDetail(this.stockInfo.detail.warnId);
          this.$refs.warnDia.checkNav(1);
        }, 100);
      }
    },
    async editCheck() {
      if (this.stockInfo.detail.optionId == 0) {
        const res = await post_insert({
          securityType: this.stockInfo.detail.securityType,
          symbol: this.stockInfo.detail.symbol,
          market: this.stockInfo.detail.market,
        });
        if (res.code != 1) return this.$message.error(res.msg);
        this.flasher();
        this.$emit("reflashs");
        return this.$message.success(res.msg);
      } else {
        const confirmInfo = await this.$confirm(
          this.$t("info.info_stock.56hzuwqar4s0"),
          this.$t("info.info_stock.56hzcquar4s0"),
          {
            confirmButtonText: this.$t("info.info_stock.56hzcquarao0"),
            cancelButtonText: this.$t("info.info_stock.56hzcquariw0"),
            type: "warning",
          }
        ).catch((err) => err);
        if (confirmInfo !== "confirm")
          return this.$message.info(this.$t("info.info_stock.56hzcquarow0"));
        const res = await post_optional_delete({
          id: this.stockInfo.detail.optionId,
        });
        if (res.code != 1) return this.$message.error(res.msg);
        // 取消自选成功，刷新列表
        this.flasher();
        this.$emit("reflashs");
        return this.$message.success(res.msg);
      }
    },
  },
  watch: {
    fixed(val) {},
    "$store.state.index.StockData": {
      handler(val) {
        if (val !== "" && val.symbol != "") {
          this.$nextTick(() => {
            this.Details_data = val;
            this.getDetail();
          });
        }
      },
      deep: true,
      immediate: true,
    },
    "$store.state.wsModel.quotation": {
      handler(val, old) {
        var _this = this;
        if (val != "") {
          // _this.$forceUpdate();
          let data = JSON.parse(val);
          _this.$nextTick(() => {
            _this.$set(_this.qutationData, "latestPrice", data[4]);
            _this.$set(
              _this.qutationData,
              "gain",
              (data[4] - data[8]) / data[8]
            );
            _this.$set(_this.qutationData, "chg", data[4] - data[8]);
          });
        }
      },
      deep: true,
    },
    stockInfo: {
      handler(val, old) {
        var _this = this;
        if (val != "") {
          if(val.detail.market == "US" && val.market.status !== 2) {
            // 美股需显示盘前盘后标题，因此K线高度需多减去标题盒子高度
            _this.$nextTick(()=> {
              _this.childHeight = $(".homeCenter").height() - 80 - 40;
              console.log("误解",_this.childHeight)
            })
          }else 
           _this.$nextTick(()=> {
              _this.childHeight = $(".homeCenter").height() - 80;
             })
          if (_this.setSymbolTime) {
            clearInterval(_this.setSymbolTime); //关闭
            _this.setSymbolTime = null;
          }
          // _this.$forceUpdate();
          _this.$nextTick(() => {
            _this.$set(
              _this.qutationData,
              "latestPrice",
              val.detail.latestPrice
            );
            _this.$set(_this.qutationData, "gain", val.detail.gain);
            _this.$set(_this.qutationData, "chg", val.detail.chg);
          });
          if (val.detail.market == "SZSE" || val.detail.market == "SSE") {
            // 当前为沪深股且行情等级为1，5秒刷
            if (_this.level.CN.level == 1) {
              _this.setSymbolTime = setInterval(() => {
                _this.getDetail();
              }, 5000);
            }
          }
        }
      },
      deep: true,
    },
  },
  computed: {
    stockInfo() {
      return this.$store.state.index.stockInfo;
    },
    level() {
      return this.$store.state.index.level;
    },
  },
};
</script>
<style lang="less">
@import "~@/assets/less/tip_dialog";
.stock_info {
  // width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .stock_info_top {
    border-bottom: 1px solid @LightBorderLine;
    padding: 0 10px;
    font-size: 14px;
    color: @fff;
    line-height: 38px;
    img {
      margin-right: 10px;
      height: 22px;
      width: 22px;
      cursor: pointer;
    }
    span.latestPrice {
      padding-right: 20px;
      margin-left: 20px;
    }
    span {
      margin-right: 10px;
    }
    .rightIcon {
      float: right;
      img {
        width: 20px;
      }
    }
  }
  .stock_info_type {
    height: calc(100% - 39px);
    .el-tabs__header {
      margin-bottom: 0;
      .el-tabs__item {
        font-size: 12px;
        color: @fbSix;
        //padding: 0 20px;
      }
      .el-tabs__item.is-top:nth-child(2) {
        padding-left: 20px;
      }
      .el-tabs__item.is-active {
        color: @hoverColor;
      }
      .el-tabs__active-bar {
        background-color: @hoverColor;
      }
    }
    .el-tabs__nav-wrap::after {
      height: 1px;
      background: @LightBorderLine;
    }
  }
  .panQH {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: @fff;
    font-size: 12px;
    width: 100%;
    box-sizing: border-box;
    background-color: @bgColor;
    padding: 10px 15px;
    .pan_left {
      display: flex;
      align-items: center;
      .pan_title {
        display: flex;
        align-items: center;
        margin-right: 10px;
        .label_icon {
          padding-left: 5px;
          height: 18px;
          cursor: pointer;
        }
      }
    }
    .pan_center {
      display: flex;
      .pan_item {
        margin-right: 10px;
        span {
          margin-right: 10px;
        }
      }
    }
    .pan_right {
      .time {
        margin-right: 10px;
        margin-left: 20px;
      }
    }
  }
}
.pan_data {
  span {
    margin-right: 8px;
  }
}
@media screen and (max-width: 1440px) {
  .stock_info .panQH {
    position: relative;
    display: block;
    .pan_right {
      float: right;
      margin-top: -49px;
    }
  }
}
</style>